package net.jueb.protobufs3.server;

import net.jueb.protobufs3.pojo.MessageProto;
import net.jueb.protobufs3.pojo.MessageProto.Message;
import net.jueb.protobufs3.pojo.MessageProto.MessageType;
import net.jueb.protobufs3.pojo.MessageProto.Result;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class ProtobufServerHandler extends ChannelHandlerAdapter {

	private Message buildResult(int msgId, int resultCode, String resultinfo) {
		Message.Builder msgBuilder = Message.newBuilder();// 消息主体
		msgBuilder.setMsgId(msgId);// 消息主体ID
		msgBuilder.setMsgType(MessageType.Type_Result);// 携带消息类型
		// 构建result实体类
		Result result = Result.newBuilder().setCode(resultCode)
				.setInfo(resultinfo).build();
		// 把result装入扩展
		msgBuilder.setExtension(MessageProto.result, result);
		return msgBuilder.build();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		Message m = (Message) msg;
		if (m == null) {
			return;
		}
		switch (m.getMsgType().getNumber()) {
		case MessageType.Type_Regist_VALUE:
			System.out.println("收到注册请求:" + m.getExtension(MessageProto.regist));
			ctx.writeAndFlush(buildResult(Thread.currentThread().hashCode(), 1,
					"RegistOk"));
			break;
		case MessageType.Type_Login_VALUE:
			System.out.println("收到登录请求:" + m.getExtension(MessageProto.login));
			ctx.writeAndFlush(buildResult(Thread.currentThread().hashCode(), 2,
					"LoginOk"));
			break;
		default:
			System.out.println("收到请求:" + m);
			break;
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
